/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.pacs.tools;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;

/**
 *
 * @author 52461
 */
public class DicomImage {

    public static void main(String[] args) throws IOException, InterruptedException {
        ImageReader imageReader = _getImageReader(new File("C:\\data\\1.3.6.1.4.1.36280.1.0.1.1.2016102794917.88610.14.dcm"));
        if (imageReader == null) {
            System.out.println("Cannot decode ");
            System.exit(1);
        }

        // Read the first image
        BufferedImage bi = imageReader.read(0);

        BufferedImage bi_out = new BufferedImage(bi.getWidth(),
                bi.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
        bi_out.createGraphics().drawImage(bi, 0, 0, null);
        File f_out = new File("e:/tmp/1.jpg");
        f_out.delete();
        bi_out.createGraphics().drawImage(bi, 0, 0, null);
        ImageIO.write(bi_out, "jpeg", f_out);
        while(true){
        Thread.sleep(10000);
        }
    }

    public void saveImage(String dicomPath, String targerImage) {
        ImageReader imageReader = null;
        try {
             imageReader = _getImageReader2(new File(dicomPath));

            if (imageReader != null) {
                // Read the first image
                BufferedImage bi = imageReader.read(0);

                BufferedImage bi_out = new BufferedImage(bi.getWidth(),
                        bi.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
                bi_out.createGraphics().drawImage(bi, 0, 0, null);
                File f_out = new File(targerImage);
                //f_out.delete();
                //bi_out.createGraphics().drawImage(bi, 0, 0, null);
                ImageIO.write(bi_out, "jpeg", f_out);
               
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        finally{
            try {
                ((ImageInputStream)imageReader.getInput()).close();
            } catch (IOException ex) {
               ex.printStackTrace();
            }
        }
    }
private ImageReader _getImageReader2(File file) throws IOException
    {
	Object input = new FileImageInputStream(file);
	Object origInput = input;

	// First look for a magic number in the header
	Iterator iter = ImageIO.getImageReaders(input);

	// No Image Reader is found
	if ( !iter.hasNext() ) {

	    // Then look in the directory of the file (e.g., ANALYZE, AFNI)
	    input = file;
	    iter = ImageIO.getImageReaders(input);

	    // No Image Reader is found
	    if( !iter.hasNext() ) {
		input = origInput;

		// Then look at the file name suffix
		String temp = file.getName();
		String[] strings = temp.split("\\.");

		if (strings.length > 1) {
		    int l = strings.length;
		    String suffix = strings[l-1];
		    iter = ImageIO.getImageReadersBySuffix(suffix);
		}
		if ( !iter.hasNext() ) {
		    if (strings.length > 2) {
			int l = strings.length;
			String suffix = strings[l-2] + "." + strings[l-1];
			iter = ImageIO.getImageReadersBySuffix(suffix);
		    }
		}

		// No Image Reader found
		if ( !iter.hasNext() ) { return null; }
	    }
	}

	// Set the Input Stream of the first Image Reader returned
	ImageReader imageReader = (ImageReader)iter.next();
	imageReader.setInput(input);

	// Return the Image Reader
	return imageReader;
    }

     private static ImageReader _getImageReader(File file) {
        Object input = null;
        try {
            //input_image = new FileImageInputStream(file);
            input = new FileImageInputStream(file);
            
            Object origInput = input;
            
            // First look for a magic number in the header
            Iterator iter = ImageIO.getImageReaders(input);

            // No Image Reader is found
            if (!iter.hasNext()) {
                System.out.println("0000000000000");
                // Then look in the directory of the file (e.g., ANALYZE, AFNI)
                input = file;
                iter = ImageIO.getImageReaders(input);

                // No Image Reader is found
                if (!iter.hasNext()) {
                    input = origInput;

                    // Then look at the file name suffix
                    String temp = file.getName();
                    String[] strings = temp.split("\\.");

                    if (strings.length > 1) {
                        int l = strings.length;
                        String suffix = strings[l - 1];
                        iter = ImageIO.getImageReadersBySuffix(suffix);
                    }
                    if (!iter.hasNext()) {
                        if (strings.length > 2) {
                            int l = strings.length;
                            String suffix = strings[l - 2] + "." + strings[l - 1];
                            iter = ImageIO.getImageReadersBySuffix(suffix);
                        }
                    }

                    // No Image Reader found
                    if (!iter.hasNext()) {
                        return null;
                    }
                }
            }

            // Set the Input Stream of the first Image Reader returned
            ImageReader imageReader = (ImageReader) iter.next();
            
            imageReader.setInput(input);

            // Return the Image Reader
            return imageReader;
        } catch (IOException ex) {
           
            return null;
        }

    }
}
